package cn.thoughtworks.school.configrations;

import cn.thoughtworks.school.services.UserCenterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

public class PermissionInterceptor implements HandlerInterceptor {
  @Autowired
  private UserCenterService userCenterService;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) throws Exception {
    String uri = request.getServletPath();

    if (!needToInterceptUrl(uri)) {
      return true;
    }

    Long id = Long.parseLong(request.getHeader("id"));
    if (hasPermission(id, uri)) {
      return true;
    }

    httpServletResponse.setStatus(403);
    return false;

  }

  private boolean hasPermission(Long id, String uri) {
    if (matchPublishRole(uri)) {
      return userCenterService.hasPublishRole(id);
    }
    if (matchAdminRole(uri)) {
      return userCenterService.hasAdminRole(id);
    }
    return false;
  }

  private boolean matchPublishRole(String uri) {
    return publishRoleUrls().stream().anyMatch(uri::matches);
  }

  private boolean matchAdminRole(String uri) {
    return adminRoleUrls().stream().anyMatch(uri::matches);
  }

  private String getTokenHeader(HttpServletRequest request) {
    return request.getHeader("token");
  }

  private boolean needToInterceptUrl(String uri) {
    return matchPublishRole(uri) || matchAdminRole(uri);
  }

  private List<String> publishRoleUrls() {
    return Arrays.asList(
      "/api/videos/my",
      "/api/serials/my",
      "/api/applications"
    );
  }

  private List<String> adminRoleUrls() {
    return Arrays.asList(
      "/api/publishers/\\s+",
      "/api/publishers/\\d+",
      "/api/publishers"
    );
  }

}
